<template>
  <!-- 产品选择对话框 -->
  <el-dialog
    v-model="visible"
    title="选择产品"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="产品名称">
          <el-input
            v-model="searchForm.product_name"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter="handleSearch"
            style="width: 150px;"
          />
        </el-form-item>

        <el-form-item label="产品编码">
          <el-input
            v-model="searchForm.product_code"
            placeholder="请输入产品编码"
            clearable
            @keyup.enter="handleSearch"
            style="width: 150px;"
          />
        </el-form-item>

        <el-form-item label="产品分类">
          <el-select
            v-model="searchForm.category_id"
            placeholder="请选择产品分类"
            clearable
            style="width: 150px;"
            @change="handleSearch"
          >
            <el-option
              v-for="category in categoryOptions"
              :key="category.category_id"
              :label="category.category_name"
              :value="category.category_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 产品数据表格 -->
    <el-table
      border
      :data="productList"
      :show-overflow-tooltip="true"
      highlight-current-row
      @current-change="handleCurrentChange"
      v-loading="loading"
      height="400"
    >
      <el-table-column prop="product_id" label="编号" width="60" />
      <el-table-column prop="product_name" label="产品名称" />
      <el-table-column prop="product_code" label="产品编码" />
      <el-table-column prop="category.category_name" label="分类" />
      <el-table-column prop="retail_price" label="零售价" />
      <el-table-column prop="wholesale_price" label="批发价" />
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 对话框底部操作区域 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="!selectedProduct">
          确定选择
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, watch, onMounted } from 'vue'
import { getProductList } from '@/api/Products'
import { getProductCategoryList } from '@/api/ProductCategories'
import { ElMessage } from 'element-plus'

// 定义props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['update:modelValue', 'select'])

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const productList = ref([])
const selectedProduct = ref(null)
const categoryOptions = ref([])

// 分页相关数据
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单数据
const searchForm = reactive({
  product_name: '',
  product_code: '',
  category_id: ''
})

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    // 打开对话框时获取产品列表和分类选项
    getProductListData()
    getCategoryOptions()
  }
})

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
})

/**
 * 获取产品分类选项
 */
const getCategoryOptions = async () => {
  try {
    const res = await getProductCategoryList({ pageSize: 1000 })
    categoryOptions.value = res.data || []
  } catch (error) {
    console.error('获取产品分类列表失败:', error)
    ElMessage.error('获取产品分类列表失败，请稍后重试！')
  }
}

/**
 * 获取产品列表数据
 */
const getProductListData = async () => {
  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    product_name: searchForm.product_name,
    product_code: searchForm.product_code,
    category_id: searchForm.category_id
  }

  try {
    loading.value = true
    const res = await getProductList(params)

    productList.value = res.data || []
    total.value = res.pagination.totalCount
    currentPage.value = res.pagination.currentPage
    pageSize.value = res.pagination.pageSize
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败，请稍后重试！')
  } finally {
    loading.value = false
  }
}

/**
 * 页码改变事件处理函数
 */
const handlePageChange = (page) => {
  currentPage.value = page
  getProductListData()
}

/**
 * 每页条数改变事件处理函数
 */
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getProductListData()
}

/**
 * 搜索功能处理函数
 */
const handleSearch = () => {
  currentPage.value = 1
  getProductListData()
}

/**
 * 重置搜索条件处理函数
 */
const handleReset = () => {
  searchForm.product_name = ''
  searchForm.product_code = ''
  searchForm.category_id = ''
  currentPage.value = 1
  getProductListData()
}

/**
 * 表格行选中处理函数
 */
const handleCurrentChange = (row) => {
  selectedProduct.value = row
}

/**
 * 确认选择处理函数
 */
const handleConfirm = () => {
  if (!selectedProduct.value) {
    ElMessage.warning('请先选择一个产品')
    return
  }

  emit('select', selectedProduct.value)
  handleClose()
}

/**
 * 关闭对话框处理函数
 */
const handleClose = () => {
  visible.value = false
  selectedProduct.value = null
  // 重置搜索条件
  searchForm.product_name = ''
  searchForm.product_code = ''
  searchForm.category_id = ''
  currentPage.value = 1
}

// 组件挂载时获取分类选项
onMounted(() => {
  getCategoryOptions()
})

// 暴露方法给父组件
defineExpose({
  getProductListData
})
</script>

<style scoped>
.search-container {
  margin-bottom: 15px;
}

.search-form {
  margin-bottom: 0;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.pagination-container {
  text-align: right;
  margin-top: 15px;
}

.dialog-footer {
  text-align: right;
}
</style>
